<template>
    <div class="i18n-management">
        <!-- 顶部操作栏 -->
        <div class="page-header">
            <h2>国际化信息</h2>
            <div class="action-buttons">
                <el-button type="default" @click="handleExport('json')">
                    <i class="iconfont icon-daochu"></i> 导出JSON
                </el-button>
                <el-button type="default" @click="handleExport('csv')">
                    <i class="iconfont icon-daochu"></i> 导出CSV
                </el-button>
                <el-button type="default" @click="importDialogVisible = true">
                    <i class="iconfont icon-shangchuan"></i> 导入
                </el-button>
                <el-button type="primary" @click="openCreateDialog">
                    <i class="iconfont icon-tianjia"></i> 新建
                </el-button>
                <el-button type="default" @click="fetchI18nData">
                    <i class="iconfont icon-xuanzhuan"></i> 刷新
                </el-button>
                <el-button type="default" disabled>
                    <i class="iconfont icon-shezhichilun"></i> 设置
                </el-button>
                <el-button type="default" disabled>
                    <i class="iconfont icon-LiftingTable"></i> 导入模板
                </el-button>
            </div>
        </div>

        <!-- 搜索框 -->
        <div class="search-container">
            <el-input 
                v-model="searchCode" 
                placeholder="输入国际化标识关键词(如:HOME_)" 
                style="width: 300px"
                @keyup.enter="handleSearch"
                clearable
                @clear="handleSearch"
            />
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px">搜索</el-button>
            <el-button type="default" @click="resetSearch" style="margin-left: 10px">重置</el-button>
        </div>

        <!-- 国际化列表表格 -->
        <el-table 
            :data="i18nList" 
            border 
            style="width: 100%" 
            v-loading="loading"
            :empty-text="emptyText"
        >
            <el-table-column prop="id" label="ID" width="80" align="center" />
            <el-table-column prop="langTag" label="语言标签" width="120" align="center" />
            <el-table-column prop="i18nKey" label="国际化标识" min-width="180" show-overflow-tooltip />
            <el-table-column prop="textValue" label="文本值" min-width="200" show-overflow-tooltip />
            <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
            <el-table-column label="操作" width="120" align="center" fixed="right">
                <template #default="scope">
                    <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" link @click="deleteI18n(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination 
                v-model:current-page="currentPage" 
                v-model:page-size="pageSize" 
                :total="total"
                :page-sizes="[10, 20, 50, 100]" 
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" 
                @current-change="handleCurrentChange" 
                background
            />
        </div>

        <!-- 新建/编辑弹窗 -->
        <el-dialog 
            v-model="dialogVisible" 
            :title="dialogTitle" 
            width="600px"
            :close-on-click-modal="false"
            @closed="handleDialogClosed"
        >
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="国际化标识" prop="i18nKey">
                    <el-input 
                        v-model="form.i18nKey" 
                        placeholder="输入国际化标识（如：HOME_TITLE）" 
                        :disabled="isEdit"
                        maxlength="100"
                        show-word-limit
                    />
                </el-form-item>

                <el-form-item label="语言文本" prop="languages" class="language-form-item">
                    <div class="language-list">
                        <div v-for="(item, index) in form.languages" :key="index" class="language-item">
                            <el-input 
                                v-model="item.langTag" 
                                placeholder="语言标签（如：zh-CN）"
                                style="width: 120px; margin-right: 10px" 
                                maxlength="20"
                            />
                            <el-input 
                                v-model="item.textValue" 
                                placeholder="文本值" 
                                style="flex: 1; margin-right: 10px" 
                                maxlength="500"
                                show-word-limit
                            />
                            <el-button 
                                type="danger" 
                                link 
                                :icon="Remove"
                                @click="removeLanguage(index)"
                                v-if="form.languages.length > 1"
                            />
                        </div>
                    </div>

                    <div class="add-field-container">
                        <el-button type="primary" link :icon="Plus" @click="addLanguage">
                            添加语言字段
                        </el-button>
                    </div>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input 
                        type="textarea" 
                        v-model="form.remark" 
                        placeholder="输入备注信息" 
                        :rows="3" 
                        maxlength="200"
                        show-word-limit
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 导入弹窗 -->
        <el-dialog 
            v-model="importDialogVisible" 
            title="导入国际化数据" 
            width="500px"
            :close-on-click-modal="false"
            @closed="handleImportDialogClosed"
        >
            <el-form :model="importForm" ref="importFormRef" label-width="100px">
                <el-form-item label="文件格式">
                    <el-radio-group v-model="importForm.format">
                        <el-radio label="json">JSON</el-radio>
                        <el-radio label="csv">CSV</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="文件上传" prop="file">
                    <el-upload 
                        class="upload-demo" 
                        action="" 
                        :auto-upload="false" 
                        :on-change="handleFileChange"
                        :on-remove="handleFileRemove" 
                        accept=".json,.csv" 
                        :file-list="fileList"
                        :limit="1"
                    >
                        <el-button type="primary">选择文件</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                支持 JSON 或 CSV 格式文件，CSV表头需为：<code>code,languageTag,message,remarks</code>
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="importDialogVisible = false">取消</el-button>
                    <el-button 
                        type="primary" 
                        @click="handleImportSubmit" 
                        :disabled="!importForm.file"
                        :loading="importing"
                    >
                        确认导入
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Plus, Remove } from '@element-plus/icons-vue'
import request from '@/utils/request'
import '../icon/iconfont.css'

// 常量定义
const API_PREFIX = '/i18n'
const DEFAULT_LANGUAGES = [
    { langTag: 'zh-CN', textValue: '' },
    { langTag: 'en-US', textValue: '' },
]

// 响应式数据
const i18nList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const importDialogVisible = ref(false)
const formRef = ref(null)
const importFormRef = ref(null)
const isEdit = ref(false)
const searchCode = ref('')
const fileList = ref([])
const submitting = ref(false)
const importing = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表单数据
const form = reactive({
    i18nKey: '',
    languages: [...DEFAULT_LANGUAGES],
    remark: '',
})

// 导入表单数据
const importForm = reactive({
    format: 'json',
    file: null,
})

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑国际化信息' : '新建国际化信息')
const emptyText = computed(() => loading.value ? '加载中...' : '暂无数据')

// 表单校验规则
const rules = {
    i18nKey: [
        { required: true, message: '请输入国际化标识', trigger: 'blur' },
        { pattern: /^[A-Z][A-Z0-9_]*$/, message: '标识必须以大写字母开头，只能包含字母、数字和下划线', trigger: 'blur' }
    ],
    languages: [
        {
            required: true,
            validator: (rule, value, callback) => {
                if (!value || value.length === 0) {
                    callback(new Error('至少需要一种语言配置'))
                    return
                }
                
                const hasEmpty = value.some(item => !item.langTag.trim() || !item.textValue.trim())
                if (hasEmpty) {
                    callback(new Error('语言标签和文本值不能为空'))
                    return
                }
                
                const langTags = value.map(item => item.langTag)
                const hasDuplicate = new Set(langTags).size !== langTags.length
                if (hasDuplicate) {
                    callback(new Error('语言标签不能重复'))
                    return
                }
                
                callback()
            },
            trigger: 'blur',
        },
    ],
}

// 工具函数
const getToken = () => localStorage.getItem('token') || ''

const formatI18nData = (data) => {
    return data.map(item => ({
        id: item.id,
        i18nKey: item.code,
        langTag: item.language_tag,
        textValue: item.message,
        remark: item.remarks || '',
        createTime: item.created_at
    }))
}

const showLoading = (text = '加载中...') => ElLoading.service({ text, lock: true })

// API 调用函数
const fetchI18nData = async () => {
    loading.value = true
    try {
        const params = {
            current: currentPage.value,
            currentSize: pageSize.value,
        }

        // 只有当有搜索条件时才添加code参数
        if (searchCode.value.trim()) {
            params.code = searchCode.value.trim()
        }

        const res = await request.get(`${API_PREFIX}/list`, {
            params,
            headers: { Authorization: `Bearer ${getToken()}` }
        })

        if (res.code === 200) {
            i18nList.value = formatI18nData(res.data.records || [])
            total.value = res.data.total || 0
        } else {
            throw new Error(res.message || '数据加载失败')
        }
    } catch (error) {
        console.error('获取国际化列表失败:', error)
        ElMessage.error(error.message || '数据加载失败')
        i18nList.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

const createI18n = async () => {
    submitting.value = true
    try {
        const data = {
            code: form.i18nKey,
            remarks: form.remark,
            languageTexts: form.languages.map(item => ({
                languageTag: item.langTag,
                message: item.textValue
            })),
        }

        const res = await request.post(`${API_PREFIX}/create`, data, {
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${getToken()}`
            }
        })

        if (res.code === 200) {
            ElMessage.success('创建成功')
            dialogVisible.value = false
            fetchI18nData()
        } else {
            throw new Error(res.message || '创建失败')
        }
    } catch (error) {
        console.error('创建国际化数据失败:', error)
        ElMessage.error(error.message)
    } finally {
        submitting.value = false
    }
}

const updateI18n = async () => {
    submitting.value = true
    try {
        const data = {
            code: form.i18nKey,
            remarks: form.remark,
            languageTexts: form.languages.map(item => ({
                languageTag: item.langTag,
                message: item.textValue
            })),
        }

        const res = await request.post(`${API_PREFIX}/update`, data, {
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${getToken()}`
            }
        })

        if (res.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            fetchI18nData()
        } else {
            throw new Error(res.message || '更新失败')
        }
    } catch (error) {
        console.error('更新国际化数据失败:', error)
        ElMessage.error(error.message)
    } finally {
        submitting.value = false
    }
}

const deleteI18n = async (row) => {
    try {
        await ElMessageBox.confirm(
            `确认删除${row.i18nKey}？此操作不可恢复`,
            '删除确认',
            {
                confirmButtonText: '确认删除',
                cancelButtonText: '取消',
                type: 'error',
                center: true
            }
        )

        const res = await request.delete(`${API_PREFIX}/delete/${row.i18nKey}`, {
            headers: { Authorization: `Bearer ${getToken()}` }
        })

        if (res.code === 200) {
            ElMessage.success(`成功删除【${row.i18nKey}】`)
            // 如果当前页最后一条数据被删除，且不是第一页，则跳转到前一页
            if (i18nList.value.length === 1 && currentPage.value > 1) {
                currentPage.value--
            }
            fetchI18nData()
        } else {
            throw new Error(res.message || '删除失败')
        }
    } catch (error) {
        if (!error.toString().includes('cancel')) {
            console.error('删除失败:', error)
            ElMessage.error(error.message)
        }
    }
}

const handleExport = async (format = 'json') => {
    const loadingInstance = showLoading('导出中...')
    try {
        const params = {
            format,
            languageTags: 'zh-CN,en-US',
            download: true,
            filename: `i18n-data-${new Date().getTime()}`,
        }

        // 移除不必要的参数
        delete params.filename // API中filename是可选的，不是必须参数

        const res = await request.get(`${API_PREFIX}/export`, {
            params,
            responseType: 'blob',
            headers: { Authorization: `Bearer ${getToken()}` }
        })

        // 检查响应类型
        if (res instanceof Blob) {
            const blob = res
            const contentDisposition = res.headers?.['content-disposition']
            let filename = `i18n-export-${new Date().getTime()}.${format}`
            
            // 从响应头中提取文件名
            if (contentDisposition) {
                const filenameMatch = contentDisposition.match(/filename="?(.+)"?/i)
                if (filenameMatch && filenameMatch[1]) {
                    filename = filenameMatch[1]
                }
            }

            const url = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.href = url
            a.download = filename
            document.body.appendChild(a)
            a.click()

            setTimeout(() => {
                document.body.removeChild(a)
                URL.revokeObjectURL(url)
            }, 100)

            ElMessage.success('导出成功')
        } else {
            // 如果不是Blob响应，可能是错误信息
            console.error('导出响应格式错误:', res)
            ElMessage.error('导出失败：响应格式不正确')
        }
    } catch (error) {
        console.error('导出失败:', error)
        
        // 尝试解析错误信息
        if (error.response?.data instanceof Blob) {
            try {
                const errorText = await error.response.data.text()
                const errorData = JSON.parse(errorText)
                ElMessage.error(errorData.message || '导出失败')
            } catch {
                ElMessage.error('导出失败：服务器错误')
            }
        } else {
            ElMessage.error('导出失败：' + (error.message || '未知错误'))
        }
    } finally {
        loadingInstance.close()
    }
}

const handleImportSubmit = async () => {
    if (!importForm.file) {
        ElMessage.warning('请选择文件')
        return
    }

    importing.value = true
    const loadingInstance = showLoading('导入中...')
    try {
        const formData = new FormData()
        formData.append('file', importForm.file)
        
        // 根据API文档，format参数是可选的，可以自动识别
        // 只有在需要覆盖自动识别时才添加format参数
        if (importForm.format) {
            formData.append('format', importForm.format)
        }

        const res = await request.post(`${API_PREFIX}/import`, formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                Authorization: `Bearer ${getToken()}`
            }
        })

        if (res.code === 200) {
            ElMessage.success('导入成功')
            importDialogVisible.value = false
            resetImportForm()
            fetchI18nData()
        } else {
            throw new Error(res.message || '导入失败')
        }
    } catch (error) {
        console.error('导入失败:', error)
        ElMessage.error(error.message || '导入失败')
    } finally {
        importing.value = false
        loadingInstance.close()
    }
}

// UI 交互函数
const openCreateDialog = () => {
    isEdit.value = false
    resetForm()
    dialogVisible.value = true
    nextTick(() => {
        formRef.value?.clearValidate()
    })
}

const handleEdit = async (row) => {
    isEdit.value = true
    loading.value = true
    try {
        const res = await request.get(`${API_PREFIX}/list`, {
            params: { code: row.i18nKey },
            headers: { Authorization: `Bearer ${getToken()}` }
        })

        if (res.code === 200 && res.data.records.length > 0) {
            const records = res.data.records
            const languageMap = {}
            records.forEach(item => {
                languageMap[item.language_tag] = item.message
            })

            form.i18nKey = row.i18nKey
            form.remark = records[0].remarks || ''
            form.languages = Object.entries(languageMap).map(([tag, msg]) => ({
                langTag: tag,
                textValue: msg
            }))

            dialogVisible.value = true
        } else {
            throw new Error('获取编辑数据失败')
        }
    } catch (error) {
        console.error('获取编辑数据失败:', error)
        ElMessage.error(error.message)
    } finally {
        loading.value = false
    }
}

const submitForm = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                updateI18n()
            } else {
                createI18n()
            }
        }
    })
}

const addLanguage = () => {
    form.languages.push({ langTag: '', textValue: '' })
}

const removeLanguage = (index) => {
    form.languages.splice(index, 1)
}

const handleFileChange = (file) => {
    importForm.file = file.raw
}

const handleFileRemove = () => {
    importForm.file = null
}

const handleSearch = () => {
    currentPage.value = 1
    fetchI18nData()
}

const resetSearch = () => {
    searchCode.value = ''
    currentPage.value = 1
    fetchI18nData()
}

const resetForm = () => {
    form.i18nKey = ''
    form.remark = ''
    form.languages = [...DEFAULT_LANGUAGES]
}

const resetImportForm = () => {
    fileList.value = []
    importForm.file = null
    importForm.format = 'json'
}

const handleDialogClosed = () => {
    formRef.value?.clearValidate()
}

const handleImportDialogClosed = () => {
    resetImportForm()
    importFormRef.value?.clearValidate()
}

const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    fetchI18nData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchI18nData()
}

// 生命周期
onMounted(() => {
    fetchI18nData()
})
</script>

<style scoped>
.i18n-management {
    padding: 20px;
    background-color: #fafbfc;
    min-height: calc(100vh - 100px);
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.page-header h2 {
    font-size: 20px;
    font-weight: 600;
    margin: 0;
    color: #303133;
    padding-left: 10px;
    border-left: 4px solid #409eff;
}

.action-buttons {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.action-buttons .el-button {
    display: flex;
    align-items: center;
}

.action-buttons .iconfont {
    margin-right: 5px;
}

.search-container {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    gap: 10px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.el-table {
    --el-table-header-text-color: #606266;
    --el-table-row-hover-bg-color: #f5f7fa;
    --el-table-border-color: #ebeef5;
    background-color: #fff;
}

.el-table th {
    background-color: #f5f7fa !important;
    font-weight: 600;
}

.language-form-item {
    margin-bottom: 20px;
}

.language-list {
    margin-bottom: 10px;
}

.language-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    gap: 8px;
}

.add-field-container {
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    padding: 12px;
    text-align: center;
    background-color: #fafafa;
    transition: border-color 0.3s;
}

.add-field-container:hover {
    border-color: #409eff;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.upload-demo {
    width: 100%;
}

.upload-demo .el-upload {
    width: 100%;
}

:deep(.el-upload-list__item) {
    transition: none !important;
}

@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }

    .action-buttons {
        width: 100%;
        justify-content: flex-start;
    }

    .search-container {
        flex-direction: column;
        align-items: flex-start;
    }

    .search-container .el-input {
        width: 100% !important;
        margin-bottom: 10px;
    }

    .language-item {
        flex-direction: column;
        align-items: stretch;
    }

    .language-item .el-input {
        width: 100% !important;
        margin-right: 0 !important;
        margin-bottom: 8px;
    }
}
</style>